import cloud from '@lafjs/cloud'
let dbName = "web-realInfo"
const db = cloud.database();
let data

export default async function (ctx: FunctionContext) {
  data = ctx.body.data


  switch (ctx.body.type) {
    case "add":
      return add()
      break;
    case "update":
      return update()
      break;
    case "del":
      return delFunc()
      break;
    case "list":
      return list()
      break;
    case "details":
      return details()
      break;
    default://不分页查询
      return Search()
      break;
  }
}

async function details() {
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: data
  });
  return cloud.utils.requestReturn({ data: res })
}

async function add() {
  await cloud.nw.db.add({
    dbName,
    dataJson: data,
    cancelAddTime: true
  });
  await sortData()
  return cloud.utils.requestReturn({ data: "" })
}

async function list() {
  let query = { ...data }
  delete query._id
  delete query.pageIndex
  delete query.pageSize
  query = cloud.utils.extractValidKeys(query)

  let res = await cloud.nw.db.select({
    dbName,
    getCount: true,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize,
    whereJson: query,
    sortArr: [
      { "name": "sort", "type": "asc" },
    ],
  });
  return cloud.utils.requestReturn({ data: res })
}

async function delFunc() {
  await cloud.nw.db.del({
    dbName,
    whereJson: { _id: data._id }
  });
  await sortData()
  return cloud.utils.requestReturn({ data: "" })
}

async function update() {
  let query = { ...data }
  delete query._id
  await cloud.nw.db.update({
    dbName,
    whereJson: { _id: data._id, },
    dataJson: query
  });
  await sortData()
  return cloud.utils.requestReturn({ data: "" })
}

async function Search() {
  let { data } = await db.collection(dbName).get()
  return cloud.utils.requestReturn({ data })
}


async function sortData() {
  let arr = <any>[]  //精选的数据
  let list = <any>[]
  let { data } = await db.collection(dbName).get()
  data.forEach(element => {
    element.timeStamp = cloud.utils.getTimeFn(element.releaseDate);
    if (element.isSelected) {
      arr.push(element)
    } else {
      list.push(element)
    }
  });
  arr = cloud.utils.sortItems([...arr], "desc", "timeStamp");
  list = cloud.utils.sortItems([...list], "desc", "timeStamp");
  let newData = arr.concat(list)
  for (let index = 0; index < newData.length; index++) {
    const element = newData[index];
    element.sort = index
    let query = { ...element }
    delete query._id
    await cloud.nw.db.update({
      dbName,
      whereJson: { _id: element._id, },
      dataJson: query
    });
  }
}